<?php
include_once 'modules/Pay.php';

// 追踪相关
class TrackAction extends BaseAction {
  /**
   * 新增追踪记录
   * @return bool 新增是否成功
   */
  public function create() {
    $Log = M('Log');
    $condition['log_post_id'] = $this->_post('log_post_id');
    $condition['log_user_openid'] = $this->_post('log_user_openid');

    $logPostId =  $this->_post('log_post_id');
    $logUserOpenId = $this->_post('log_user_openid');
    $nickname = $this->_post('log_username');
    $location = $this->_post('log_location');
    $PostDetail = M('Post')->find($logPostId);
    $title = $PostDetail['post_title'];

    $sql = "SELECT MIN(t.log_id) minLogId FROM (SELECT log_id FROM track_log WHERE log_post_id = $logPostId AND log_user_openid = '$logUserOpenId' ORDER BY log_created DESC LIMIT 20)t";
    $Model = new Model();
    $res = $Model->query($sql);
    $minLogId = $res[0]['minLogId'];
    if(!$minLogId) $minLogId = 0;
    $condition['log_id'] = array('lt', $minLogId);
    $Log->where($condition)->delete();

    $logId = parent::_modelDoAdd('Log');
    if(intval($logId) > 0 && $this->_post('first') === '1') {
      $noticeData['notice_track_id'] = $logId;
      
      $adminIds = M('Admin')->getField('admin_id', true);
      foreach ($adminIds as $adminId) {
        $noticeData['notice_admin_id'] = $adminId;
        $noticeData['notice_is_read'] = 0;
        $ret = parent::_modelDoAdd('Notice', $noticeData);

        $openIds = M('Bind')->where('bind_admin_id='.$adminId)->getField('bind_user_openid', true);
        foreach ($openIds as $openId) {
          $tplResult = $this->noticeTemplate($openId, $title, $nickname, $location, $logPostId);
          $openIdResult[] = $tplResult;
        }
      }
    }
    $this->ajaxReturn(trace(), 'success', 1);
  }

  function https_request($url,$data = null)
  {   //函数定义，数据传输万能方法
      $postData = json_encode($data);
      $headers = array("Content-type: application/json;charset=UTF-8");
      $curl = curl_init();  //
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
      if (!empty($data)) {
          curl_setopt($curl, CURLOPT_POST, 1);
          curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
          curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
      }
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
      $output = curl_exec($curl);
      curl_close($curl);
      return $output;
  }


  private function httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
    // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
    curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__).'/modules/cacert.pem');
    curl_setopt($curl, CURLOPT_URL, $url);

    $res = curl_exec($curl);
    curl_close($curl);

    return $res;
  }

  private function _getToken() {
    $appid = 'wx87cb77e727af8680';
    $appsecret = 'f5d067559835de27da9fb1d87c8888d3';
    $sessionName = 'admin_global_token';

    $data = json_decode(session($sessionName));
    if ($data->expire_time < time()) {
      // 如果是企业号用以下URL获取access_token
      // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
      $res = json_decode($this->httpGet($url));
      $access_token = $res->access_token;
      if ($access_token) {
        $data->expire_time = time() + 7000;
        $data->access_token = $access_token;
        session($sessionName, json_encode($data));
        // $this->set_php_file("access_token.php", json_encode($data));
      }
    } else {
      $access_token = $data->access_token;
    }
    return $access_token;
  }

  private function noticeTemplate($openId, $title, $nickname, $location, $postId) {
    $accessToken = $this->_getToken();
    $date = date('Y-m-d H:i:s');

    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$accessToken";
    $data['touser'] = $openId;
    $data['template_id'] = 'StxbEz06r3zsMRQW-YqH9MtKx7czW5RX8ZirAfxHGHc';
    $data['url'] = 'https://'.$_SERVER['HTTP_HOST'].'/track/web/dist/index.html#/list/detail/'.$postId;
    $data['data']['first'] = array('value' => $nickname.'打开了《'.$title.'》', 'color' => '#173177');
    $data['data']['keyword1'] = array('value' => $nickname, 'color' => '#173177');
    $data['data']['keyword2'] = array('value' => $date, 'color' => '#173177');
    $data['data']['remark'] = array('value' => '当前位置：'.$location, 'color' => '#ff0000');

    $result = $this->https_request($url, $data);
    return $result;
  }

  /**
   * 列出指定用户在指定文章下的追踪记录列表
   * @return array
   */
  public function listByPostUser() {
    $Log = M('Log');
    $condition['log_post_id'] = $this->request['log_post_id'];
    $condition['log_user_openid'] = $this->request['log_user_openid'];
    $result = $Log->where($condition)->order('log_created desc')->limit(1)->select();

    $this->ajaxReturn($result, 'success', 1);
  }

  public function wechatnotify() {
    Pay::wechatNotify();
  }

  public function checkOrder() {
    $Orders = M("Orders");
    $data = $Orders->find($this->request['id']);
    if($data['order_userid'] == $_SESSION['trackUser']['admin_id'] && $data['order_status'] == 1){
      $this->ajaxReturn('', '订单已完成', 1);
    }else{
      $this->ajaxReturn('', '订单未完成', 0);
    }
  }

  public function redpacket() {
    $postId = $this->_post('post_id');
    $openId = $this->_post('user_openid');
    $username = $this->_post('user_username');
    $avatar = $this->_post('user_avatar');
    if(!$postId || !$openId) {
      $this->ajaxReturn('', '参数不正确', 0);
    }

    $RedpacketList = M("RedpacketList");
    $condition['rp_postid'] = $postId;
    $condition['rp_status'] = 0;
    $redPacketId = $RedpacketList->where($condition)->min('rp_id');
    if($redPacketId) {
      // 获取该用户上次领取时间
      $condition['rp_status'] = 1;
      $condition['rp_owner'] = $openId;
      $lastUpdated = $RedpacketList->where($condition)->getField('rp_updated');
      $timeNow = time();
      if ($lastUpdated && ($timeNow - $lastUpdated < 60)) {
        $this->ajaxReturn('', '领取间隔过短', 0);
      }

      // 红包发放
      $ret = Pay::redpacket($redPacketId, $openId);
      if($ret['status'] === 1) {
        // 更改记录
        $saveData['rp_id'] = $redPacketId;
        $saveData['rp_owner'] = $openId;
        $saveData['rp_updated'] = $timeNow;
        $saveData['rp_status'] = 1;
        $saveData['rp_ownername'] = $username;
        $saveData['rp_avatar'] = $avatar;
        $RedpacketList->save($saveData);
        $rpData = $RedpacketList->find($redPacketId);
        $this->ajaxReturn('', '恭喜你获得一个 '.$rpData['rp_price'].' 元的红包！', 1);
      } else {
        $this->ajaxReturn($ret);
      }
    } else {
      $this->ajaxReturn(trace(), '红包已领完，下次请赶早~', 0);
    }
  }
}